import React, { PureComponent } from 'react';
import { Icon } from 'antd';
import classnames from 'classnames';
import { isFunction } from '@design/core/utils/is-object';

function ToolbarButton(props) {
  const { icon, action, getEditor, disable, title } = props;
  const onClick = () => {
    if (isFunction(action)) {
      const editor = getEditor();
      action(editor);
    }
  };
  let disabled = false;
  if (isFunction(disable)) {
    disabled = disable(getEditor);
  }
  const className = classnames('toolbar-btn', { disabled });
  return (
    <div className={className} onClick={onClick}>
      {icon && <Icon type={icon} />}
      {title}
    </div>
  );
}

class Toolbar extends PureComponent {
  renderToolbarOptions = () => {
    const { getEditor, options = [] } = this.props;
    return options.map(option => (
      <ToolbarButton key={option.key} {...option} getEditor={getEditor} />
    ));
  };

  render() {
    return <div className="toolbar">{this.renderToolbarOptions()}</div>;
  }
}

export default Toolbar;
